package com.coocaa.typhoon.api.config.redis;

import com.coocaa.cirrus.common.base.util.JsonUtil;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author bijiahao
 * @date : 2025/9/18 15:12
 * @description
 */
@Configuration
public class RedisTemplateConfig {
    @Autowired
    private RedisProperties redisProperties;

    @Primary
    @Bean("ClusterConfig")
    public RedisClusterConfiguration redisClusterConfiguration() {
        RedisClusterConfiguration configuration = new RedisClusterConfiguration();
        String nodes = redisProperties.getCluster().getNodes();
        configuration.setClusterNodes(getNodes(nodes));
        configuration.setMaxRedirects(redisProperties.getMaxRedirects());
        configuration.setPassword(redisProperties.getPassword());
        return configuration;
    }

    @Bean("ClusterPoolConfig")
    public GenericObjectPoolConfig redisClusterPool() {
        GenericObjectPoolConfig config = new GenericObjectPoolConfig();
        config.setMaxIdle(redisProperties.getLettuce().getPool().getMaxIdle());
        config.setMinIdle(redisProperties.getLettuce().getPool().getMinIdle());
        config.setMaxTotal(redisProperties.getLettuce().getPool().getMaxActive());
        config.setMaxWaitMillis(redisProperties.getLettuce().getPool().getMaxWait());
        return config;
    }

    @Bean("ClusterFactory")
    public LettuceConnectionFactory lettuceConnectionFactoryForCluster(@Qualifier("ClusterConfig") RedisClusterConfiguration redisClusterConfiguration, @Qualifier("ClusterPoolConfig") GenericObjectPoolConfig poolConfig) {
        LettucePoolingClientConfiguration lettuceClientConfiguration = LettucePoolingClientConfiguration.builder()
                .commandTimeout(Duration.ofMillis(Long.parseLong(redisProperties.getTimeout())))
                .poolConfig(poolConfig)
                .build();
        return new LettuceConnectionFactory(redisClusterConfiguration, lettuceClientConfiguration);
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate(@Qualifier("ClusterFactory") LettuceConnectionFactory factory) {
        return RedisTemplateConfig.newRedisTemplate(factory);
    }

    @Bean
    public StringRedisTemplate stringRedisTemplate(@Qualifier("ClusterFactory") LettuceConnectionFactory factory) {
        return new StringRedisTemplate(factory);
    }

    public static RedisTemplate<String, Object> newRedisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(lettuceConnectionFactory);
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        template.setKeySerializer(stringRedisSerializer);
        template.setHashKeySerializer(stringRedisSerializer);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }

    public static List<RedisNode> getNodes(String hosts) {
        if (StringUtils.isBlank(hosts)) {
            return Collections.emptyList();
        }
        String[] hostList = hosts.split(",");
        List<RedisNode> redisNodes = new ArrayList<>(hostList.length);
        for (String host : hostList) {
            String url = getUrl(host);
            Integer port = getPort(host);
            redisNodes.add(new RedisNode(url, port));
        }
        return redisNodes;
    }

    private static String getUrl(String host) {
        return host.split(":")[0];
    }

    private static Integer getPort(String host) {
        return Integer.parseInt(host.split(":")[1]);
    }
}
